package com.lam.common.components.easyexcel.handlers;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;

import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.lam.common.utils.CollectionUtil;

/**
 * 批注生成Handler
 * @author lam
 *
 */
public class RowCommentWriteHandler implements RowWriteHandler {
	
	protected Map<Integer, String> commentData = new HashMap<>();
	
	protected Font defaultFont;

	public RowCommentWriteHandler() {}
	
	public RowCommentWriteHandler(Map<Integer, String> commentData) {
		this.commentData = commentData;
	}
	
	protected Font getDefaultFont(Sheet sheet) {
		if(defaultFont != null) {
			return defaultFont;
		}
		
		defaultFont = sheet.getWorkbook().createFont();
		defaultFont.setFontHeightInPoints((short)10);
        return defaultFont;
	}

	@Override
    public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
            Integer relativeRowIndex, Boolean isHead) {
        
    	if(CollectionUtil.isNotEmpty(commentData)) {
            Sheet sheet = writeSheetHolder.getSheet();
            Drawing<?> drawingPatriarch = sheet.createDrawingPatriarch();
            for (Entry<Integer, String> entry : commentData.entrySet()) {
            	Integer col1 = entry.getKey();
            	Integer col2 = col1 + 2;
            	 // 在第一行 第二列创建一个批注
	            Comment comment = drawingPatriarch.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, 
	            		col1.shortValue(), 0, col2.shortValue(), 2));
	            XSSFRichTextString ts = new XSSFRichTextString(entry.getValue());
	            ts.applyFont(getDefaultFont(sheet));
	            // 输入批注信息
	            comment.setString(ts);
	            // 将批注添加到单元格对象中
	            sheet.getRow(0).getCell(col1).setCellComment(comment);
			}
        }
    }

	public Map<Integer, String> getCommentData() {
		return commentData;
	}

	public RowCommentWriteHandler setCommentData(Map<Integer, String> commentData) {
		this.commentData = commentData;
		return this;
	}

	@Override
	public void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Integer rowIndex,
			Integer relativeRowIndex, Boolean isHead) {
	}

	@Override
	public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
			Integer relativeRowIndex, Boolean isHead) {
	}
	
}
